package com.quectel.mobile.controller.invoice;

import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.constant.core.invoice.InvoiceConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.module.household.dto.HouseholdDto;
import com.quectel.core.module.invoice.dto.InvoiceTitleDto;
import com.quectel.core.module.invoice.service.InvoiceTitleService;
import com.quectel.mobile.controller.BaseController;
import com.quectel.mobile.util.SessionHolder;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/4/21 10:56
 * @description new java file header...
 */
@RestController
@RequestMapping("invoiceTitle")
@Tag(name = "InvoiceTitleController", description = "Mobile端-住户开票记录相关api")
public class InvoiceTitleController extends BaseController {
    @DubboReference
    private InvoiceTitleService invoiceTitleService;

    /**
     * 分页查询
     *
     * @return
     */
    @GetMapping("queryAll")
    @Operation(summary = "所有抬头查询")
    public Response<List<InvoiceTitleDto>> queryAll(
            @Parameter(description = "开票类型1企业2个人") @RequestParam(required = false) String typeFlag,
            @Parameter(description = "发票抬头名称") @RequestParam(required = false) String titleFlag
    ) {
        //查询列表数据
        Request request = Request.configParamsNotPage(Request.parseParams(httpServletRequest));

        //必须认证过的住户
        HouseholdDto currentHousehold = SessionHolder.getLoginMobileUserSession().getCurrentHousehold();
        if (currentHousehold == null) {
            return Response.<List<InvoiceTitleDto>>ok().wrap(Collections.emptyList());
        }

        request.put(LambdaUtil.getFieldName(InvoiceTitleDto::getTenantId), String.valueOf(currentHousehold.getTenantId()));
        request.put(LambdaUtil.getFieldName(InvoiceTitleDto::getPersonType), InvoiceConstants.PersonSourceTypeEnum.HOUSEHOLD.getPersonSourceType());
        request.put(LambdaUtil.getFieldName(InvoiceTitleDto::getPersonId), String.valueOf(currentHousehold.getId()));
        request.put(LambdaUtil.getFieldName(InvoiceTitleDto::getType), typeFlag);
        request.put(LambdaUtil.getFieldName(InvoiceTitleDto::getTitle), titleFlag);

        int total = invoiceTitleService.queryTotal(request.getParams());

        List<InvoiceTitleDto> list = null;
        if (total > 0) {
            list = invoiceTitleService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        return Response.<List<InvoiceTitleDto>>ok().wrap(list);
    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @Operation(summary = "分页列表")
    public Response<Page<InvoiceTitleDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize,
            @Parameter(description = "开票类型1企业2个人") @RequestParam(required = false) String typeFlag,
            @Parameter(description = "发票抬头名称") @RequestParam(required = false) String titleFlag
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        SessionHolder.checkMobileUser();
        SessionHolder.checkHousehold();

        HouseholdDto currentHousehold = SessionHolder.getLoginMobileUserSession().getCurrentHousehold();

        request.put(LambdaUtil.getFieldName(InvoiceTitleDto::getTenantId), String.valueOf(currentHousehold.getTenantId()));
        request.put(LambdaUtil.getFieldName(InvoiceTitleDto::getPersonType), InvoiceConstants.PersonSourceTypeEnum.HOUSEHOLD.getPersonSourceType());
        request.put(LambdaUtil.getFieldName(InvoiceTitleDto::getPersonId), String.valueOf(currentHousehold.getId()));
        request.put(LambdaUtil.getFieldName(InvoiceTitleDto::getType), typeFlag);
        request.put(LambdaUtil.getFieldName(InvoiceTitleDto::getTitle), titleFlag);

        int total = invoiceTitleService.queryTotal(request.getParams());

        List<InvoiceTitleDto> list = null;
        if (total > 0) {
            list = invoiceTitleService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<InvoiceTitleDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<InvoiceTitleDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @Operation(summary = "查询单条记录")
    public Response<InvoiceTitleDto> infoForEdit(@PathVariable("id") Long id) {
        SessionHolder.checkMobileUser();
        SessionHolder.checkHousehold();

        HouseholdDto currentHousehold = SessionHolder.getLoginMobileUserSession().getCurrentHousehold();

        Map<String, Object> params = new HashMap<>();
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        params.put(LambdaUtil.getFieldName(InvoiceTitleDto::getTenantId), String.valueOf(currentHousehold.getTenantId()));
        params.put(LambdaUtil.getFieldName(InvoiceTitleDto::getPersonType), InvoiceConstants.PersonSourceTypeEnum.HOUSEHOLD.getPersonSourceType());
        params.put(LambdaUtil.getFieldName(InvoiceTitleDto::getPersonId), String.valueOf(currentHousehold.getId()));

        if (invoiceTitleService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        InvoiceTitleDto invoiceTitleDto = invoiceTitleService.selectById(id);

        return Response.<InvoiceTitleDto>ok().wrap(invoiceTitleDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @Operation(summary = "查询单条记录")
    public Response<InvoiceTitleDto> info(@PathVariable("id") Long id) {

        SessionHolder.checkMobileUser();
        SessionHolder.checkHousehold();

        HouseholdDto currentHousehold = SessionHolder.getLoginMobileUserSession().getCurrentHousehold();

        Map<String, Object> params = new HashMap<>();
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        params.put(LambdaUtil.getFieldName(InvoiceTitleDto::getTenantId), String.valueOf(currentHousehold.getTenantId()));
        params.put(LambdaUtil.getFieldName(InvoiceTitleDto::getPersonType), InvoiceConstants.PersonSourceTypeEnum.HOUSEHOLD.getPersonSourceType());
        params.put(LambdaUtil.getFieldName(InvoiceTitleDto::getPersonId), String.valueOf(currentHousehold.getId()));

        if (invoiceTitleService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        InvoiceTitleDto invoiceTitleDto = invoiceTitleService.selectById(id);

        return Response.<InvoiceTitleDto>ok().wrap(invoiceTitleDto);
    }

    /**
     * 保存
     *
     * @param invoiceTitleDto
     * @return
     */
    @PostMapping("save")
    @Operation(summary = "保存单条记录")
    public Response<Object> save(@RequestBody @Validated InvoiceTitleDto invoiceTitleDto) {
        SessionHolder.checkMobileUser();
        SessionHolder.checkHousehold();

        HouseholdDto currentHousehold = SessionHolder.getLoginMobileUserSession().getCurrentHousehold();

        invoiceTitleDto.setTenantId(currentHousehold.getTenantId());
        invoiceTitleDto.setVillageId(currentHousehold.getVillageId());
        invoiceTitleDto.setPersonType(InvoiceConstants.PersonSourceTypeEnum.HOUSEHOLD.getPersonSourceType());
        invoiceTitleDto.setPersonId(currentHousehold.getId());

        invoiceTitleDto.setCreator(currentHousehold.getName());
        invoiceTitleDto.setCreateTime(new Date());

        // 是否默认1是0否
        if (invoiceTitleDto.getIsDefault().equals(InvoiceConstants.isDefaultStatus.YES.getType())) {
            // 更新此用户其他的默认地址为非默认
            Map<String, Object> params = new HashMap<>();
            params.put(LambdaUtil.getFieldName(InvoiceTitleDto::getTenantId), String.valueOf(currentHousehold.getTenantId()));
            params.put(LambdaUtil.getFieldName(InvoiceTitleDto::getPersonType), InvoiceConstants.PersonSourceTypeEnum.HOUSEHOLD.getPersonSourceType());
            params.put(LambdaUtil.getFieldName(InvoiceTitleDto::getPersonId), String.valueOf(currentHousehold.getId()));

            List<InvoiceTitleDto> invoiceTitleDtos = invoiceTitleService.queryList(params);
            if (CollectionUtils.isNotEmpty(invoiceTitleDtos)) {
                for (InvoiceTitleDto dto : invoiceTitleDtos) {
                    InvoiceTitleDto newlyDto = new InvoiceTitleDto();
                    newlyDto.setId(dto.getId());
                    newlyDto.setIsDefault(InvoiceConstants.isDefaultStatus.NO.getType());
                    invoiceTitleService.updateById(newlyDto);
                }
            }
        }

        //填充基础数据
        invoiceTitleService.save(invoiceTitleDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param invoiceTitleDto
     * @return
     */
    @PostMapping("update")
    @Operation(summary = "修改单条记录")
    public Response<Object> update(@RequestBody @Validated InvoiceTitleDto invoiceTitleDto) {

        SessionHolder.checkMobileUser();
        SessionHolder.checkHousehold();

        HouseholdDto currentHousehold = SessionHolder.getLoginMobileUserSession().getCurrentHousehold();

        Map<String, Object> params = new HashMap<>();
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(invoiceTitleDto.getId()));
        params.put(LambdaUtil.getFieldName(InvoiceTitleDto::getTenantId), String.valueOf(currentHousehold.getTenantId()));
        params.put(LambdaUtil.getFieldName(InvoiceTitleDto::getPersonType), InvoiceConstants.PersonSourceTypeEnum.HOUSEHOLD.getPersonSourceType());
        params.put(LambdaUtil.getFieldName(InvoiceTitleDto::getPersonId), String.valueOf(currentHousehold.getId()));

        if (invoiceTitleService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        invoiceTitleDto.setEditor(currentHousehold.getName());
        invoiceTitleDto.setEditTime(new Date());

        // 是否默认1是0否
        if (invoiceTitleDto.getIsDefault().equals(InvoiceConstants.isDefaultStatus.YES.getType())) {
            // 更新此用户其他的默认地址为非默认
            Map<String, Object> queryParams = new HashMap<>();
            queryParams.put(LambdaUtil.getFieldName(InvoiceTitleDto::getTenantId), String.valueOf(currentHousehold.getTenantId()));
            queryParams.put(LambdaUtil.getFieldName(InvoiceTitleDto::getPersonType), InvoiceConstants.PersonSourceTypeEnum.HOUSEHOLD.getPersonSourceType());
            queryParams.put(LambdaUtil.getFieldName(InvoiceTitleDto::getPersonId), String.valueOf(currentHousehold.getId()));

            List<InvoiceTitleDto> invoiceTitleDtos = invoiceTitleService.queryList(queryParams);
            if (CollectionUtils.isNotEmpty(invoiceTitleDtos)) {
                for (InvoiceTitleDto dto : invoiceTitleDtos) {
                    InvoiceTitleDto newlyDto = new InvoiceTitleDto();
                    newlyDto.setId(dto.getId());
                    newlyDto.setIsDefault(InvoiceConstants.isDefaultStatus.NO.getType());
                    invoiceTitleService.updateById(newlyDto);
                }
            }
        }

        invoiceTitleService.updateById(invoiceTitleDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @Operation(summary = "批量删除记录")
    public Response<Object> delete(@RequestBody Long[] ids) {
        SessionHolder.checkMobileUser();
        SessionHolder.checkHousehold();

        HouseholdDto currentHousehold = SessionHolder.getLoginMobileUserSession().getCurrentHousehold();

        Map<String, Object> params = new HashMap<>();

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
            params.put(LambdaUtil.getFieldName(InvoiceTitleDto::getTenantId), String.valueOf(currentHousehold.getTenantId()));
            params.put(LambdaUtil.getFieldName(InvoiceTitleDto::getPersonType), InvoiceConstants.PersonSourceTypeEnum.HOUSEHOLD.getPersonSourceType());
            params.put(LambdaUtil.getFieldName(InvoiceTitleDto::getPersonId), String.valueOf(currentHousehold.getId()));

            if (invoiceTitleService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        invoiceTitleService.deleteBatch(ids);

        return Response.ok();
    }

}
